<template>
  <!-- 添加或修改客户端对话框 -->
  <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
    <el-form ref="clientFormRef" :model="formData" :rules="rules" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户端ID" prop="clientId">
            <el-input v-model="formData.clientId" placeholder="请输入客户端ID" :disabled="formData.clientId !== ''" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户端名称" prop="clientName">
            <el-input v-model="formData.clientName" placeholder="请输入客户端名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户端类型" prop="clientType">
            <el-select v-model="formData.clientType" placeholder="请选择客户端类型" style="width: 100%">
              <el-option label="设备客户端" value="device" />
              <el-option label="应用客户端" value="app" />
              <el-option label="网关客户端" value="gateway" />
              <el-option label="第三方客户端" value="third_party" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="协议类型" prop="protocol">
            <el-select v-model="formData.protocol" placeholder="请选择协议类型" style="width: 100%">
              <el-option label="MQTT" value="MQTT" />
              <el-option label="CoAP" value="CoAP" />
              <el-option label="HTTP" value="HTTP" />
              <el-option label="WebSocket" value="WebSocket" />
              <el-option label="TCP" value="TCP" />
              <el-option label="UDP" value="UDP" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="认证方式" prop="authType">
            <el-select v-model="formData.authType" placeholder="请选择认证方式" style="width: 100%">
              <el-option label="用户名密码" value="username_password" />
              <el-option label="证书认证" value="certificate" />
              <el-option label="Token认证" value="token" />
              <el-option label="无认证" value="none" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="IP地址" prop="ipAddress">
            <el-input v-model="formData.ipAddress" placeholder="请输入IP地址" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="端口" prop="port">
            <el-input-number v-model="formData.port" :min="1" :max="65535" placeholder="请输入端口" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio label="1">启用</el-radio>
              <el-radio label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="认证信息" prop="authInfo" v-if="formData.authType !== 'none'">
        <el-input v-model="formData.authInfo" type="textarea" :rows="3" placeholder="请输入认证信息（JSON格式）" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" type="textarea" :rows="2" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="ClientFormDialog" lang="ts">
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'

// 定义组件属性
interface Props {
  visible: boolean
  title: string
  formData: any
}

// 定义事件
interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'submit'): void
  (e: 'cancel'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const clientFormRef = ref()

// 对话框状态
const dialog = reactive({
  visible: false,
  title: ''
})

// 表单数据
const form = reactive({
  clientId: '',
  clientName: '',
  clientType: '',
  protocol: '',
  authType: '',
  ipAddress: '',
  port: null,
  status: '1',
  authInfo: '',
  remark: ''
})

// 表单验证规则
const rules = reactive({
  clientId: [{ required: true, message: '客户端ID不能为空', trigger: 'blur' }],
  clientName: [{ required: true, message: '客户端名称不能为空', trigger: 'blur' }],
  clientType: [{ required: true, message: '客户端类型不能为空', trigger: 'change' }],
  protocol: [{ required: true, message: '协议类型不能为空', trigger: 'change' }],
  authType: [{ required: true, message: '认证方式不能为空', trigger: 'change' }],
  ipAddress: [{ required: true, message: 'IP地址不能为空', trigger: 'blur' }],
  port: [{ required: true, message: '端口不能为空', trigger: 'blur' }]
})

// 处理表单数据，将空字符串转换为undefined
const processFormData = (data: any) => {
  const processed = { ...data }
  Object.keys(processed).forEach(key => {
    if (processed[key] === '') {
      processed[key] = undefined
    }
  })
  return processed
}

// 监听props变化
watch(() => props.visible, (newVal) => {
  dialog.visible = newVal
})

watch(() => props.title, (newVal) => {
  dialog.title = newVal
})

watch(() => props.formData, (newVal) => {
  if (newVal) {
    const processedData = processFormData(newVal)
    Object.assign(form, processedData)
  } else {
    resetForm()
  }
}, { deep: true })

watch(() => dialog.visible, (newVal) => {
  emit('update:visible', newVal)
})

// 提交表单
const handleSubmit = () => {
  clientFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      emit('submit')
    }
  })
}

// 取消操作
const handleCancel = () => {
  dialog.visible = false
  // 清除表单验证状态
  clientFormRef.value?.clearValidate()
  emit('cancel')
}

// 重置表单
const resetForm = () => {
  form.clientId = ''
  form.clientName = ''
  form.clientType = ''
  form.protocol = ''
  form.authType = ''
  form.ipAddress = ''
  form.port = null
  form.status = '1'
  form.authInfo = ''
  form.remark = ''
  clientFormRef.value?.resetFields()
}

// 暴露方法给父组件
defineExpose({
  resetForm
})
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>